import requests
import json
from urllib import parse
from hyper.contrib import HTTP20Adapter


# url参数unicode编码获取
class UrlEncode:
    url = 'https://tool.lu/encdec/ajax.html'
    Form_data = {}
    Headers = {}

    def __init__(self):
        self.Form_data = {
            # 需要进行encode/decode的内容
            'code': '',
            # 操作，urlencode/urldecode，或其他更多编解码，具体的到https://tool.lu/encdec/查看
            'operate': 'urlencode'
        }

        self.Headers = {
            ':authority': 'tool.lu',
            ':method': 'POST',
            ':path': '/encdec/ajax.html',
            ':scheme': 'https',
            'accept': 'application/json, text/javascript, */*; q=0.01',
            'accept-encoding': 'gzip, deflate, br',
            'accept-language': 'zh-CN,zh;q=0.9',
            'content-length': '',
            'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'cookie': 'uuid=d6d0f5a7-19a2-4451-c422-a7200618e2ef; '
                      'slim_session=%7B%22slim.flash%22%3A%5B%5D%7D; '
                      'Hm_lvt_0fba23df1ee7ec49af558fb29456f532=1626312298,1626333229,1626405346,1627262926; '
                      'Hm_lpvt_0fba23df1ee7ec49af558fb29456f532=1627264849; '
                      '_access=0e728b216629c8f2a3d1f698dc383e24805470ce66c430272a8ce6af27285a03',
            'origin': 'https://tool.lu',
            'referer': 'https://tool.lu/encdec/',
            'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
            'sec-ch-ua-mobile': '?0',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36',
            'x-requested-with': 'XMLHttpRequest'
        }

    def setRequestData(self, src):
        self.Form_data['code'] = src
        self.Headers['content-length'] = str(len(parse.urlencode(self.Form_data).encode('utf-8')))

    def urlEncode(self, src):
        # 设置请求参数
        self.setRequestData(src)

        # 获取编码结果
        sessions = requests.session()
        sessions.mount("https://tool.lu/", HTTP20Adapter())
        response = sessions.post(self.url, data=self.Form_data, headers=self.Headers)
        # 由于Headers中有":"开头的参数，这是http2的请求，导致请求头无法被解析，因此需要使用hyper帮助解析
        # response = requests.post(self.url, data=self.Form_data, headers=self.Headers)
        result = json.loads(response.text)
        # print(result)
        if 'text' in result:
            try:
                result = result['text']
                return result
            except:
                pass
        return None


if __name__ == '__main__':
    urlencode = UrlEncode()
    print(urlencode.urlEncode('酒泉'))
